package com.helloworld;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import com.google.gson.Gson;
import com.helloworld.bean.CityBean;
import com.weiwangcn.betterspinner.library.BetterSpinner;

import java.util.ArrayList;
import java.util.List;

public class BetterSpinnerActivity extends AppCompatActivity {

    BetterSpinner spinner;
    BetterSpinner spinnerCity;
    private String  jsonCity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_better_spinner);
        String[] list = getResources().getStringArray(R.array.month);
        spinner= (BetterSpinner) findViewById(R.id.spinner);
        spinnerCity= (BetterSpinner) findViewById(R.id.spinner_city);
        initData();

    }
    CityBean cityBean;
    private void initData() {
        jsonCity=getResources().getString(R.string.city_list);
         cityBean=new Gson().fromJson(jsonCity,CityBean.class);
        List<String> mList=new ArrayList<>();
        for (int i=0;i<cityBean.getProvinces().size();i++){
            String provice=cityBean.getProvinces().get(i).getProvinceName();
            mList.add(provice);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, mList);
        spinner.setAdapter(adapter);
        spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<String> mCityList=new ArrayList<String>();
                String province= (String) parent.getAdapter().getItem(position);

                for (int i=0;i<cityBean.getProvinces().size();i++){
                    CityBean.ProvincesBean provincesBean=cityBean.getProvinces().get(i);
                    if (province.equals(provincesBean.getProvinceName())){
                        for (int j=0;j<provincesBean.getCitys().size();j++){
                            CityBean.ProvincesBean.CitysBean citysBean=provincesBean.getCitys().get(i);

                            String city=citysBean.getCitysName();
                            mCityList.add(city);
                        }
                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(BetterSpinnerActivity.this,
                        android.R.layout.simple_dropdown_item_1line, mCityList);
                spinnerCity.setAdapter(adapter);
            }
        });
    }
}
